//index.js
//获取应用实例
const app = getApp()
const requestUtil = require("../../../utils/request");
const api = require("../../../config/api");
const util = require("../../../utils/util");
const common = require("../../../utils/common");

Page({
  data: {
    pickerList: null,
    itemList: null,
    clazzList: null,
    pickerName: null,
    pickerIndex: 0, // 左上角选择索引
    selectedGrade: null, // 左上角选择的年级
    selectedClazz: null, // 左上角选择的班级
    isPickerChange: false,
    userInfo: null,
    currentTermInfo: {}, // 当前学期信息
    termList: null, // 全部学期信息
    termListIndex: 0, // 选择的index
    name: null, // 用户名字
    userType: 1, // 用户类型
    tabArray: [], // tab数组，老师和家长有所不同
    messageTabArray: ['全部', '成绩', '通知', '作业', '打卡', '图文'],
    messageTabString: '全部', // tab选了的项
    approvalTabArray: ['未审核', '已审核'],
    TabCur: 1, // tab项有用
    MessageTabCur: 0, // 班级消息圈的tab有用
    AppraisalTab: 0, // 文明班级评比tab有用
    ApprovalTab: 0, // 文明班级评比组长级别Tab有用
    scrollLeft: 0, // message tab的偏移量
    termExamList: [], // 考试数据列表,
    firstTimeToRegister: false, // 首次跳转到注册页面

    pageSize: 10, // 每页显示数
    pageNum: 1, // 页码
    weekNo: null, // 周id
    appraisalList: [], // 评比数据
    appraisalListTotal: 0, // 页面总数
    waitingAppraisalNum: 0, // 未审批总数
    noMoreAppraisal: false, // 数据是否还有更多
    currDutyTeacherInfo: null, // 值周老师相关数据
    dutyTeacherType: 0, // 评比老师类型，0无权限，1组员，2组长，3值周行政
    isLeader: false,//值周行政
    isHead: false,//组长
    isMember: false,//组员
    evaLeaderType: 0, // 负责人类型，0无权限，1板块负责人，2总负责人,
    teacherGradeName: '',
    banZhuRenClass: '',
    plateType: null, // 板块类型
    plateTypeList: [],//板块负责人的板块类型
    rejectReason: null, // 驳回评价理由
    gradeList: [], // 年级列表
    gradeListIndex: 0, // 年级列表索引
    plateListIndex: 0, // 板块列表索引
    weekList: [], // 年级列表
    weekListIndex: 0, // 星期列表索引,
    isSubscribe: false,
    isOnload: false,
    appraisalAdminTableHeader: [{
      prop: 'grade',
      width: 130,
      label: '年级'
    }, {
      prop: 'clazz',
      width: 130,
      label: '班级'
    }, {
      prop: 'teacherName',
      width: 150,
      label: '班主任'
    }, {
      prop: 'weekRank',
      width: 150,
      label: '本周排名'
    }, {
      prop: 'weekScore',
      width: 150,
      label: '本周分数'
    }, {
      prop: 'termRank',
      width: 150,
      label: '学期排名'
    }, {
      prop: 'termScore',
      width: 150,
      label: '学期分数'
    }, {
      prop: 'detail',
      width: 150,
      label: '班级详情'
    }], // 板块负责人评比表头
    appraisalAdminTableList: [], // 板块负责人评比表格数据
    appraisalLeaderTableHeader: [{
        prop: 'grade',
        width: 130,
        label: '年级'
      }, {
        prop: 'clazz',
        width: 130,
        label: '班级'
      }, {
        prop: 'teacherName',
        width: 150,
        label: '班主任'
      }, {
        prop: 'weekRank',
        width: 150,
        label: '本周排名'
      },
      {
        prop: 'weekScore',
        width: 150,
        label: '本周分数'
      },
      {
        prop: 'termRank',
        width: 150,
        label: '学期排名'
      },
      {
        prop: 'termScore',
        width: 150,
        label: '学期总分'
      },
      {
        prop: 'detail',
        width: 150,
        label: '班级详情'
      }
    ], // 总负责人评比表头
    appraisalLeaderTableList: [], // 总负责人评比表格数据
    border: true,
    tableNoDataMsg: '暂无数据',
    scoreType: 'add', // 组长确认审批框默认值，add加分，sub扣分
    agreeAppraisalScore: null, // 确认审批默认分数

  },
  onLoad: function () {
    wx.showLoading({
      title: '加载中...',
      mask: true
    });
    if (!app.globalData.isInitTeacher && !app.globalData.isInitParent) {
      app.registerCallback = () => {
        if (getCurrentPages()[getCurrentPages().length - 1].route === 'pages/my/register/register') {
          return;
        } else {
          wx.redirectTo({
            url: '../../my/register/register?type=0',
          })
        }
      }
    }
    let canIShow = app.globalData.canIShow;
    if (!canIShow) {
      app.loginCallback = () => {
        this.onShowCall();
      }
      app.globalData.canIShow = true;
    } else {
      this.onShowCall();
    }
  },

  onReady: function () {
    wx.hideLoading()
  },
  onHide: function () {
    //FIXME 切换页面后重置学期选择
    // let firstTermInfo = this.data.termList[0];
    // this.setData({
    //   termListIndex: 0,
    //   currentTermInfo: firstTermInfo
    // })
    if (app.globalData.switchTab) {
      this.setData({
        TabCur: 0,
      })
    }
  },

  /**
   * 用户上拉触底的事件
   */
  onReachBottom: function () {
    wx.showLoading({
      title: '加载中......',
      mask: true
    });
    let maxNum = Math.ceil(this.data.appraisalListTotal / this.data.pageSize);
    let num = this.data.pageNum + 1; // 页码+1
    if (num <= maxNum) {
      this.setData({
        pageNum: num
      });
      this.getRegList(this.data.confId, this.data.ApprovalTab);
    } else {
      this.setData({
        noMoreAppraisal: true
      })
    }
    wx.hideLoading();
  },

  /**
   * 下拉刷新
   */
  onPullDownRefresh: function () {
    if (this.data.tabArray[this.data.TabCur] == '文明班级评比') {
      wx.showLoading({
        title: '加载中......',
        mask: true
      });
      this.setData({
        noMoreAppraisal: false,
        pageNum: 1,
        appraisalList: [],
      });
      this.getRegList(this.data.confId, this.data.ApprovalTab);
      wx.hideLoading();
    }else if(this.data.tabArray[this.data.TabCur] == '班级评比统计') {
      this.getTotal();
    }
    wx.stopPullDownRefresh();
  },

  onShow: function () {
    if(this.data.isOnload) this.onPullDownRefresh();
    // if (!canIShow) {
    //   app.loginCallback = () => {
    //     this.onShowCall();
    //   }
    //   app.globalData.canIShow = true;
    // } else {
    //   this.onShowCall();
    // }
  },
  /**
   * onShow的响应函数
   */
  onShowCall: function () {
    app.globalData.loadShow = true;

    // 如果是切换角色来的就重置TabCur
    if (app.globalData.switchTab) {
      this.setData({
        TabCur: 0
      })
      app.globalData.switchTab = false;
    }

    let userType = app.globalData.userType;
    let tabArr = [];
    let userInfo = {};
    let date = util.formatDate(new Date);


    if (userType == 1) { // 如果用户角色类型为老师
      tabArr = ['班级消息圈'];
      userInfo = app.globalData.teacherInfo[0];
    } else { // 如果用户角色类型为家长
      tabArr = ['班级消息圈'];
      userInfo = app.globalData.parentInfo[0];
    }


    // 如果没绑定信息就不显示数据
    if (userInfo == null || JSON.stringify(userInfo) == '{}') {
      if (!this.data.firstTimeToRegister) {
        this.toRegisterWithTeacher(userType);
      } else {
        wx.showToast({
          title: '请先绑定信息',
          icon: 'none',
        })
      }
      this.setData({
        termExamList: null,
        pickerList: null,
        userInfo: null,
        tabArray: tabArr,
        TabCur: tabArr.length == 1 ? 0 : this.data.TabCur,
        firstTimeToRegister: true,
      })
      return null;
    }

    // 设置左上角的数据
    this.setTopPicker(userType);
    // 获取当前学期信息
    this.setCurrentTermInfo();
    // 获取全部学期信息
    this.getTermList(userInfo);

    this.setData({
      currentDate: date,
      userType: userType,
      tabArray: tabArr,
      TabCur: tabArr.length == 1 ? 0 : this.data.TabCur,
      userInfo: userInfo,
      isOnload: true
    });
    this.getCurrDutyTeacher();
  },
  /**
   * 转发
   * 暂时没要这部分
   */
  onShareAppMessage: function (o) {
    let grade = o.target.dataset.grade;
    let id = o.target.dataset.id;
    let examName = o.target.dataset.name;
    let teacherReturnObj = {
      title: examName,
      path: '../../score-page/teacher-view-score/teacher-view-score?grade=' + grade + "&examId=" + id,
      imageUrl: '../../../img/main.png'
    }
    let parentReturnObj = {
      //TODO 能不能放长图？
    };
    if (this.data.userType == 1) {
      return teacherReturnObj;
    } else {
      return parentReturnObj;
    }
  },
  /**
   * 设置左上角的选项
   */
  setTopPicker: function (userType) {
    let userInfo;
    let pickerList = [];
    let clazzList = [];
    let itemList = [];
    if (userType == 1) {
      userInfo = app.globalData.teacherInfo;
      for (let i of userInfo) {
        let str = i.gradeName + i.clazz + '班';
        pickerList.push(str);
        let obj = {
          clazzName: str,
          clazzNo: i.clazz,
          studyType: i.studyType,
          grade: i.grade
        }
        clazzList.push(obj);
        itemList.push(i.clazz);
      }
    } else {
      userInfo = app.globalData.parentInfo;
      for (let i of userInfo) {
        let str = i.studentName + '(' + i.gradeName + i.clazz + '班' + ')';
        let obj = {
          clazzName: str,
          clazzNo: i.clazz,
          studyType: i.studyType,
          grade: i.grade
        }
        clazzList.push(obj);
        pickerList.push(str);
        itemList.push(i.studentName);
      }
    }
    app.globalData.selectedGrade = clazzList[0].grade;
    app.globalData.selectedClazz = clazzList[0].clazzNo;
    this.setData({
      pickerList,
      selectedGrade: clazzList[0].grade,
      selectedClazz: clazzList[0].clazzNo,
      clazzList,
      itemList,
      pickerName: pickerList[this.data.pickerIndex ? this.data.pickerIndex : 0]
    })
  },

  /**
   * 如果没有用户就弹出绑定界面
   * @param userType 没有绑定信息的角色
   */
  toRegisterWithTeacher: function (userType) {
    wx.navigateTo({
      url: '../../my/register/register?type=' + userType
    })
  },

  /**
   * 标题栏学生或班级选择
   */
  bindPickerChange: function (e) {
    // 判断选择项是否已经是现在的项
    if (this.data.pickerName == this.data.pickerList[e.detail.value]) {
      return;
    }
    let userType = app.globalData.userType;
    let userInfo = {};
    if (userType == 1) {
      let teacherInfo = app.globalData.teacherInfo;
      for (let i of teacherInfo) {
        if (this.data.itemList[e.detail.value] == i.clazz) {
          userInfo = i;
        }
      }
    } else if (userType == 2) {
      let parentInfo = app.globalData.parentInfo;
      for (let i of parentInfo) {
        if (this.data.itemList[e.detail.value] == i.studentName) {
          userInfo = i;
        }
      }
    }
    app.globalData.selectedGrade = this.data.clazzList[e.detail.value].grade;
    app.globalData.selectedClazz = this.data.clazzList[e.detail.value].clazzNo;
    this.setClassExamList(userInfo);
    this.setData({
      userInfo,
      selectedGrade: this.data.clazzList[e.detail.value].grade,
      selectedClazz: this.data.clazzList[e.detail.value].clazzNo,
      isPickerChange: true,
      pickerIndex: e.detail.value,
      pickerName: this.data.pickerList[e.detail.value]
    })
  },

  /**
   * 第一行tab选择
   */
  tabSelect: function (e) {
    this.setData({
      TabCur: e.currentTarget.dataset.id,
      appraisalList: [],
      pageNum: 1, // 重置分页
      noMoreAppraisal: false,
    })

    if (this.data.tabArray[e.currentTarget.dataset.id] == '班级评比统计') {
      if(app.globalData.appUser.banZhuRen) {
        this.subscribeMessage();
      }
      this.getStudentOrganize();
    } else if (this.data.tabArray[e.currentTarget.dataset.id] == '文明班级评比') {
      this.subscribeMessage();
      this.getRegList(this.data.confId);
    }
  },
  subscribeMessage: function() {
    let that = this;
    if(that.data.isSubscribe) return;
    wx.requestSubscribeMessage({
      tmplIds: ['EkRpg-h1anXdZ3mQsrQfWByStTnbAeS5b39NlQlULEs','C19BHVIGLxCzbOorVDm2rAUDHklSbJUCo8UFAXt91Zc'],
      success (res) {
        console.log(res);
        that.setData({
          isSubscribe: true
        })
      },
      fail (res) {console.log(res);}
    })
  },
  /**
   * 班级消息圈tab选择
   * //FIXME 暂时没做，wxml已注释
   */
  messageTabSelect: function (e) {
    this.setData({
      MessageTabCur: e.currentTarget.dataset.id,
      scrollLeft: (e.currentTarget.dataset.id - 1) * 60,
      messageTabString: e.currentTarget.dataset.name
    })
  },

  /**
   * 班级消息圈 - 查看详情（去考试总概况）
   */
  toExamTotalScore: function (e) {
    let userType = app.globalData.userType;
    if (userType == 1) {
      let clazzList = this.data.clazzList;
      let classId = 0;
      for (let i of clazzList) {
        if (this.data.pickerName == i.clazzName) {
          classId = i.clazzNo;
        }
      }
      wx.navigateTo({
        url: '../../score-page/teacher-subject-score/teacher-subject-score?grade=' + e.currentTarget.dataset.grade +
          "&examId=" + e.currentTarget.dataset.id +
          "&clazz=" + classId +
          "&schoolId=" + this.data.userInfo.schoolId +
          "&subjectName=" + this.data.userInfo.subject,
      })

    } else if (userType == 2) {
      wx.navigateTo({
        url: '../../score-page/student-total-score/total-score?grade=' + e.currentTarget.dataset.grade +
          "&examId=" + e.currentTarget.dataset.id +
          "&studentId=" + this.data.userInfo.studentId +
          "&studyType=" + this.data.userInfo.studyType,
      })
    }
  },

  /**
   * 班级消息圈 - 去上传成绩页面
   */
  uploadScore: function (e) {
    let clazzInfo = this.data.clazzList[this.data.pickerIndex];
    let clazz = clazzInfo.clazzNo;
    let grade = clazzInfo.grade;
    let studyType = clazzInfo.studyType;
    wx.navigateTo({
      url: '../upload-score/upload-score?grade=' + grade +
        '&clazz=' + clazz +
        '&studyType=' + studyType +
        "&examId=" + e.currentTarget.dataset.examid,
    })
  },

  /**
   * 复制邀请码
   */
  copyInviteCode: function (e) {
    wx.setClipboardData({
      data: this.data.inviteCode,
    })
  },

  /**
   * 设置当前学期信息
   */
  setCurrentTermInfo: async function () {
    let that = this;
    let res = await requestUtil.request("GET", api.getCurrentTerm, null);
    that.setData({
      currentTermInfo: res.data.data,
      termName: res.data.data.termName
    })
  },

  /**
   * 班级消息圈 - 设置页面的考试列表
   */
  setClassExamList: async function (userInfo) {
    let that = this;
    let params = {
      grade: userInfo.grade,
      schoolId: userInfo.schoolId,
      studyType: userInfo.studyType,
      termId: that.data.termList[that.data.termListIndex].id
    }
    let res = await requestUtil.request("POST", api.termExamList, params)
    that.setData({
      termExamList: res.data.data
    });
  },

  /**
   * 获取学期列表
   */
  async getTermList(userInfo) {
    let res = await requestUtil.request("GET", api.getTermList, null);
    let termList = res.data.data;
    this.setData({
      termList: termList
    })
    // 获取考试列表
    this.setClassExamList(userInfo);
  },

  /**
   * 班级消息圈 - 更改学期
   */
  termListPickerChange(e) {
    this.setData({
      termListIndex: e.detail.value
    })
    let termInfo = this.data.termList[e.detail.value]
    if (termInfo.id === this.data.currentTermInfo.id) {
      return;
    } else {
      this.setData({
        currentTermInfo: termInfo
      })
      let userInfo = this.data.userInfo;
      this.setClassExamList(userInfo);
    }
  },

  /**
   * 班级消息圈 - 显示Modal
   */
  showModal(e) {
    let modalName = e.currentTarget.dataset.target;
    if (modalName == 'rejectAppraisalModal') {
      this.setData({
        modalName: e.currentTarget.dataset.target,
        rejectId: e.currentTarget.dataset.id
      })
    } else if (modalName == 'agreeAppraisalModal') {
      let score = parseFloat(e.currentTarget.dataset.score);
      this.setData({
        modalName: e.currentTarget.dataset.target,
        agreeAppraisalId: e.currentTarget.dataset.id,
        agreeAppraisalScore: score > 0 ? score : 0 - score,
        scoreType: score > 0 ? 'add' : 'sub'
      })
    } else {
      this.setData({
        modalName: e.currentTarget.dataset.target
      })
    }
  },

  /**
   * 班级消息圈 - 隐藏modal
   */
  hideModal(e) {
    this.setData({
      modalName: null
    })
  },

  /**
   * modal跳转页面
   */
  toModalFunc(e) {
    let url = e.currentTarget.dataset.url;
    wx.navigateTo({
      url: url,
    })
  },

  /**
   * 文明班级评比 - tab选择
   */
  appraisalTabSelect(e) {
    this.setData({
      AppraisalTab: e.currentTarget.dataset.id
    })
  },

  /**
   * 审批选择
   */
  approvalTabSelect(e) {
    this.setData({
      ApprovalTab: e.currentTarget.dataset.id,
      appraisalList: [],
      pageNum: 1, // 重置分页
      noMoreAppraisal: false,
    });
    this.getRegList(this.data.currDutyTeacherInfo.id, e.currentTarget.dataset.id);
  },

  /**
   * 文明评比详情
   */
  toAppraisalDetail(e) {
    let id = e.currentTarget.dataset.id;
    let ApprovalTab = this.data.ApprovalTab;
    let dutyType = this.data.dutyTeacherType;
    wx.navigateTo({
      url: '../appraise-detail/detail?id=' + id +
        '&tabType=' + ApprovalTab +
        '&dutyType=' + dutyType,
    })
  },

  /**
   * 驳回评比
   */
  async submitReject(e) {
    let _this = this;
    let reason = _this.data.rejectReason;
    if(!reason) {
      wx.showToast({title: '请输入驳回原因',icon: 'none'});
      return;
    }
    let res = await requestUtil.request("POST", api.regAudit, {
      id: _this.data.rejectId,
      auditTeacherId: _this.data.userInfo.id,
      status: 2,
      auditReason: reason
    })
    if (res.data.code == 0) {
      wx.showToast({
        title: '已驳回',
      })
      _this.setData({
        modalName: null
      });
      setTimeout(() => {
        _this.onPullDownRefresh();
      }, 1000);
    } else {
      wx.showToast({
        title: '驳回失败，' + res.data.msg,
        icon: 'none'
      })
      console.error("提交打分失败，原因为：", res.data.msg)
    }
  },

  /**
   * 隐藏驳回的modal
   */
  hideRejectModal(e) {
    this.setData({
      modalName: null,
      rejectId: null,
      rejectReason: null
    })
  },

  /**
   * 监听驳回弹出窗的textarea输入
   */
  rejectTextareaInput(e) {
    this.setData({
      rejectReason: e.detail.value
    })
  },

  /**
   * 确认提交评比
   */
  submitAgree: async function (score) {
    let _this = this;
    let teacherId = this.data.userInfo.id;
    let res = await requestUtil.request("POST", api.regAudit, {
      id: this.data.agreeAppraisalId,
      auditTeacherId: teacherId,
      status: 1,
      score: score
    })
    if (res.data.code == 0) {
      wx.showToast({
        title: '确认成功',
      })
      setTimeout(function () {
        _this.hideAgreeModal();
        _this.onPullDownRefresh();
      }, 1000)
    } else {
      wx.showToast({
        title: '确认失败，' + res.data.msg,
        icon: 'none'
      })
      console.error("提交打分失败，原因为：", res.data.msg)
    }
  },

  /**
   * 取消打分
   */
  cancelAppraisal(e) {
    let _this = this;
    wx.showModal({
      title: '确认',
      content: '确认取消吗？',
      success: (res) => {
        if (res.confirm) {
          _this.submitCancel(e.currentTarget.dataset.id);
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },

  /**
   * 确认取消
   */
  async submitCancel(id) {
    let _this = this;
    let teacherId = this.data.userInfo.id;
    let res = await requestUtil.request("POST", api.cancelReg, {
      id: id,
      regTeacherId: teacherId,
    })
    if (res.data.code == 0) {
      wx.showToast({
        title: '取消成功',
      })
      setTimeout(() => {
        _this.onPullDownRefresh();
      }, 1000)
    } else {
      wx.showToast({
        title: '取消失败,' + res.data.msg,
        icon: 'none'
      })
      console.error("取消打分失败，原因为：", res.data.msg)
    }
  },
/**
   * 板块列表选择
   */
  plateListPickerChange(e) {
    let plateListIndex = e.detail.value;
    this.setData({
      plateListIndex: plateListIndex,
      plateType: this.data.plateTypeList[plateListIndex]
    })
    this.getPlateItemTotal();
  },
  /**
   * 年级列表选择
   */
  gradeListPickerChange(e) {
    this.setData({
      gradeListIndex: e.detail.value
    })
    if (this.data.evaLeaderType == 1 || this.data.isLeader) {
      this.getItemToal();
    } else if (this.data.evaLeaderType == 2) {
      this.getPlateItemTotal();
    }
  },

  /**
   * 星期列表选择
   */
  weekListPickerChange(e) {
    this.setData({
      weekListIndex: e.detail.value
    })
    if (this.data.evaLeaderType == 1) {
      this.getItemToal();
    } else if (this.data.evaLeaderType == 2) {
      this.getPlateItemTotal();
    }
  },

  /**
   * 获取当前周的值日老师和各个负责人
   */
  async getCurrDutyTeacher() {
    let userInfo = this.data.userInfo;
    let res = await requestUtil.request("GET", api.currDutyTeacher, {
      schoolId: userInfo.schoolId
    })
    let currDutyTeacher = res.data.data;
    let memberIds = currDutyTeacher.dutyMemberIds.split(','); // 值周组员
    let leaderIds = currDutyTeacher.dutyLeaderIds.split(','); // 值周行政
    let headIds = currDutyTeacher.dutyHeadmanIds.split(','); // 值周组长
    let ids = [];
    ids.push(leaderIds, memberIds, headIds);
    let index = -1;
    let isLeader = false;
    let isHead = false;
    let isMember = false;
    // 当角色为教师时，判断教师是否属于组长、组员角色
    if (this.data.userType == 1) {
      for (let i = 0; i < ids.length; i++) {
        for (let j = 0; j < ids[i].length; j++) {
          if (ids[i][j] == userInfo.id) {
            index = i;
            if (i == 1) {
              isMember = true;
            } else if (i == 0) {
              isLeader = true;
            } else if (i == 2) {
              isHead = true;
            }
            continue;
          }
        }
      }
    }
    if (index == -1) {
      // 没出现在id数组里，无权限观看
      this.setData({
        dutyTeacherType: 0,
        weekNo: currDutyTeacher.weekNo,
        confId: currDutyTeacher.id,
        currDutyTeacherInfo: currDutyTeacher
        // modalName: 'noAuth',
      })
      this.getEvaLeaderList();
      return;
    } else if (index == 0) {
      // 值周行政
      this.setData({
        dutyTeacherType: 3
      })
    } else if (index == 2) {
      // 组长
      this.setData({
        dutyTeacherType: 2
      })
    } else if (index == 1) {
      // 组员
      this.setData({
        dutyTeacherType: 1
      })
    }
    app.globalData.teacherCharacter.isLeader = isLeader;
    app.globalData.teacherCharacter.isHead = isHead;
    app.globalData.teacherCharacter.isMember = isMember;
    this.setData({
      isLeader: isLeader,
      isHead: isHead,
      isMember: isMember,
      currDutyTeacherInfo: currDutyTeacher, // 值周老师
      weekNo: currDutyTeacher.weekNo,
      confId: currDutyTeacher.id,
    });
    this.getEvaLeaderList();
  },

  /**
   * 获取打分记录列表
   * @params status 未审批/已审批的状态
   */
  getRegList(confId, status) {
    status = util.isNullOrEmpty(status) ? this.data.ApprovalTab : status;
    switch (status) {
      case 0:
        if (this.data.dutyTeacherType == 1) {
          this.getWaitingCancelRegList(confId);
        } else {
          this.getWaitingRegList(confId);
        }
        break;
      case 1:
        this.getFinishedRegList(confId);
        break;
    }
  },
  /**
   * 获取未审批的评分列表
   */
  async getWaitingRegList(confId) {
    let params = {
      teacherId: this.data.userInfo.id,
      status: 0,
      confId: confId,
      plateType: this.data.plateType,
      fySize: this.data.pageSize,
      fyNum: this.data.pageNum
    }
    let res = await requestUtil.request("POST", api.getRegList, params);
    if (res.data.code != 0) {
      wx.showToast({
        title: res.data.msg,
        icon: 'none',
      });
      return;
    }
    let regList = res.data.data.rows;
    let appraList = this.data.appraisalList;
    for (let j of regList) {
      appraList.push(j);
    }
    let waitingapproval = '未审核（' + res.data.data.total + '）';
    let approvalTabArray = [waitingapproval, '已审核']
    this.setData({
      appraisalList: appraList,
      approvalTabArray: approvalTabArray,
      appraisalListTotal: res.data.data.total
    });
  },
  /**
   * 获取未审批和取消的评分列表（组员要看到自己取消的记录嘛）
   */
  async getWaitingCancelRegList(confId) {
    let params1 = {
      teacherId: this.data.userInfo.id,
      status: 0,
      confId: confId,
      plateType: this.data.plateType,
      fySize: this.data.pageSize,
      fyNum: this.data.pageNum
    };
    let params2 = {
      teacherId: this.data.userInfo.id,
      status: 3,
      confId: confId,
      fySize: this.data.pageSize,
      fyNum: this.data.pageNum
    };
    // 未审批列表
    let res1 = await requestUtil.request("POST", api.getRegList, params1);
    // 取消
    //let res2 = await requestUtil.request("POST", api.getRegList, params2);
    let waitingRegList = res1.data.data.rows;
    let cancelRegList = [];//res2.data.data.rows;
    let appraList = this.data.appraisalList;
    let waitingList = [];
    let cancelList = [];
    for (let m = 0; m < appraList.length; m++) {
      if (appraList[m].status == 0) {
        waitingList.push(appraList[m]);
      } else {
        cancelList.push(appraList[m]);
      }
    }
    // 不重复就加入
    for (let m = 0; m < waitingRegList.length; m++) {
      let index = waitingList.find(item => item.id == waitingRegList[m].id);
      if (typeof index === 'undefined') {
        waitingList.push(waitingRegList[m]);
      }
    }
    for (let m = 0; m < cancelRegList.length; m++) {
      let index = cancelList.find(item => item.id == cancelRegList[m].id);
      if (typeof index === 'undefined') {
        cancelList.push(cancelRegList[m]);
      }
    }
    // 根据创建时间排序
    waitingList.sort(util.dateTimeSortBy('-', 'createTime'));
    cancelList.sort(util.dateTimeSortBy('-', 'createTime'));
    let endList = waitingList.concat(cancelList);
    let waitingapproval = '未审核（' + res1.data.data.total + '）';
    let approvalTabArray = [waitingapproval, '已审核']
    this.setData({
      appraisalList: endList,
      approvalTabArray: approvalTabArray,
      appraisalListTotal: res1.data.data.total
    });
  },
  /**
   * 获取已审批和驳回的评分列表
   */
  async getFinishedRegList(confId) {
    let params1 = {
      teacherId: this.data.userInfo.id,
      status: 1,
      confId: confId,
      plateType: this.data.plateType,
      fySize: this.data.pageSize,
      fyNum: this.data.pageNum
    };
    // 已审批列表
    let res1 = await requestUtil.request("POST", api.getRegList, params1);
    let finishedRegList = res1.data.data.rows;
    // 根据创建时间排序
    let appraList = this.data.appraisalList;
    for (let m = 0; m < finishedRegList.length; m++) {
      let index = appraList.find(item => item.id == finishedRegList[m].id);
      if (typeof index === 'undefined') {
        appraList.push(finishedRegList[m]);
      }
    }
    this.setData({
      appraisalList: appraList,
      appraisalListTotal: res1.data.data.total
    });
  },

  /**
   * 去添加文明班级评比页面
   */
  toAddApprisalPage() {
    let weekNo = this.data.currDutyTeacherInfo.weekNo;
    let confId = this.data.currDutyTeacherInfo.id;
    let weekStartDate = this.data.currDutyTeacherInfo.weekStartDate;
    let weekEndDate = this.data.currDutyTeacherInfo.weekEndDate;
    wx.navigateTo({
      url: '../appraise-mark/mark?weekNo=' + weekNo +
        '&weekStartDate=' + weekStartDate +
        '&weekEndDate=' + weekEndDate +
        '&confId=' + confId +
        '&plateType=' + this.data.plateType +
        '&isXz=' + (this.data.evaLeaderType != 0 || this.data.isLeader ? 1 : 0),
    })
  },

  /**
   * 获取负责人列表
   */
  async getEvaLeaderList() {
    let userInfo = this.data.userInfo;
    let res = await requestUtil.request("GET", api.evaLeaderList, {
      schoolId: userInfo.schoolId
    })
    let evaLeaderList = res.data.data;
    let evaLeaderType = 0; // 0无权限，1总负责人，2板块负责人
    let dutyTeacherType = this.data.dutyTeacherType;
    if (this.data.userType == 1) {
      let plateTypeList = [];
      for (let list of evaLeaderList) {
        switch (list.leaderTitle) {
          case '学校总负责人':
            let ids = list.teacherIds.split(',');
            for (let i = 0; i < ids.length; i++) {
              if (ids[i] == userInfo.id) {
                evaLeaderType = 1;
                dutyTeacherType = 4
                break;
              }
            }
            break;
          case '板块负责人':
            let plateIds = list.teacherIds.split(',');
            for (let i = 0; i < plateIds.length; i++) {
              if (plateIds[i] == userInfo.id) {
                evaLeaderType = 2;
                dutyTeacherType = 5;
                plateTypeList.push(list.plateType);
                // 设置板块类型
                this.setData({
                  plateTypeList: plateTypeList,
                  plateType: list.plateType
                });
                break;
              }
            }
            break;
        }
      }
    }
    app.globalData.teacherCharacter.evaLeaderType = evaLeaderType;
    this.setData({
      evaLeaderType: evaLeaderType,
      dutyTeacherType: dutyTeacherType
    });
    this.setTabArray();
    if (this.data.tabArray[this.data.TabCur] == '文明班级评比') {
      this.getRegList(this.data.currDutyTeacherInfo.id);
    }
    if (this.data.tabArray[this.data.TabCur] == '班级评比统计') {
      this.getStudentOrganize();
    }
  },

  /**
   * 获取年级列表
   */
  async getStudentOrganize() {
    let gradeList = [];
    if((!this.data.isLeader && this.data.evaLeaderType == 0 ) && (app.globalData.appUser.banZhuRen || app.globalData.appUser.jiZhang)) {
        let teacherList = app.globalData.appUser.teacherInfo;
        let item = teacherList[0];
        for(let i in teacherList) {
          if(app.globalData.appUser.banZhuRen && teacherList[i].isClassTeacher != null && teacherList[i].isClassTeacher == 1) {
            item = teacherList[i];
            this.setData({
              banZhuRenClass: item.clazz
            })
            break;
          }
        }
        this.setData({
          teacherGradeName: item.gradeName
        })
        gradeList.push({"grade": item.grade, "gradeName": item.gradeName, "studyType": item.studyType});
    }else {
      let res = await requestUtil.request('GET', api.studentOrganize, {
        schoolId: this.data.userInfo.schoolId
      })
      let data = res.data.data;
      for (let i of data) {
        i.subList = null;
      }
      let obj = {
        gradeName: '全部',
        studyType: 1
      }
      data.unshift(obj);
      gradeList = data;
    }
    
    this.setData({
      gradeList: gradeList
    });
    this.getWeekInfo();
  },

  /**
   * 获取周列表
   */
  async getWeekInfo() {
    let res = await requestUtil.request("GET", api.dutyWeekList, {
      schoolId: this.data.userInfo.schoolId
    })
    let currRes = await requestUtil.request("GET", api.currDutyTeacher, {
      schoolId: this.data.userInfo.schoolId
    })
    let data = res.data.data;
    let currData = currRes.data.data;
    let weekList = [];
    let weekListIndex = 0;
    for (let i in data) {
      let startDate = common.getStringMonthAndDay(data[i].weekStartDate);
      let endDate = common.getStringMonthAndDay(data[i].weekEndDate);
      let str = '第' + data[i].weekNo + '周，' + startDate + ' - ' + endDate;
      let obj = {
        termId: data[i].termId,
        termName: data[i].termName,
        weekNo: data[i].weekNo,
        date: str
      }
      weekList.push(obj);
      if (data[i].weekNo == currData.weekNo) {
        weekListIndex = i;
      }
    }
    this.setData({
      weekList,
      weekListIndex,
    });
    this.getTotal();
  },
  getTotal() {
    // 顺序不能变，防止同时是 板块负责人 和 值周行政 的后果，优先板块负责人
    if(app.globalData.appUser.banZhuRen || app.globalData.appUser.jiZhang) {
      this.getItemToal();
    }else if (this.data.evaLeaderType == 2) {
      this.getPlateItemTotal();
    } else if (this.data.evaLeaderType == 1 || this.data.isLeader) {
      this.getItemToal();
    }
  },
  /**
   * 获取总负责人的数据
   */
  async getItemToal() {
    let params = {
      schoolId: this.data.userInfo.schoolId,
      termId: this.data.weekList[this.data.weekListIndex].termId,
      weekNo: this.data.weekList[this.data.weekListIndex].weekNo,
      gradeName: this.data.gradeList[this.data.gradeListIndex].gradeName == '全部' ? null : this.data.gradeList[this.data.gradeListIndex].gradeName,
      clazz: this.data.banZhuRenClass
    }
    let res = await requestUtil.request("post", api.itemTotal, params);
    let data = res.data.data;
    let list = [];
    for (let i of data) {
      let obj = {
        grade: i.gradeName,
        weekRank: '第' + i.weekRank + '名',
        weekScore: i.weekScore + '分',
        termRank: '第' + i.termRank + '名',
        termScore: i.termScore + '分',
        clazz: i.clazz + '班',
        teacherName: i.teacherName,
        detail: '详情'
      }
      list.push(obj);
    }
    this.setData({
      appraisalLeaderTableList: list
    })
  },

  /**
   * 获取板块负责人的表格数据
   */
  async getPlateItemTotal() {
    let params = {
      schoolId: this.data.userInfo.schoolId,
      termId: this.data.weekList[this.data.weekListIndex].termId,
      weekNo: this.data.weekList[this.data.weekListIndex].weekNo,
      gradeName: this.data.gradeList[this.data.gradeListIndex].gradeName == '全部' ? null : this.data.gradeList[this.data.gradeListIndex].gradeName,
      plateType: this.data.plateTypeList[this.data.plateListIndex],
    }
    let res = await requestUtil.request("POST", api.plateItemTotal, params);
    let data = res.data.data;
    let list = [];
    for (let i of data) {
      let obj = {
        grade: i.gradeName,
        weekRank: '第' + i.weekRank + '名',
        weekScore: i.weekScore + '分',
        teacherName: i.teacherName,
        clazz: i.clazz + '班',
        termRank: '第' + i.termRank + '名',
        termScore: i.termScore + '分',
        detail: '详情'
      }
      list.push(obj);
    }
    this.setData({
      appraisalAdminTableList: list
    })
  },

  /**
   * 板块详情
   */
  plateDetail() {
    let weekNo = this.data.weekList[this.data.weekListIndex].weekNo;
    let isLeader = this.data.isLeader ? 1 : 0;
    let ApprovalTab = this.data.ApprovalTab;
    let dutyType = this.data.dutyTeacherType;
    if (this.data.evaLeaderType == 1) {
      wx.navigateTo({
        url: '../appraise-plate-detail/plate?weekNo=' + weekNo +
        '&tabType=' + ApprovalTab +
        '&dutyType=' + dutyType,
      })
    } else {
      wx.navigateTo({
        url: '../appraise-plate-detail/plate?weekNo=' + weekNo + '&isLeader=' + isLeader +
        '&tabType=' + ApprovalTab +
        '&dutyType=' + dutyType,
      })
    }
  },

  /**
   * 班级详情
   */
  clazzDetail() {
    let evaType = this.data.evaLeaderType;
    let weekNo = this.data.weekList[this.data.weekListIndex].weekNo;
    if (evaType == 2) {
      let plateType = this.data.plateType;
      wx.navigateTo({
        url: '../appraise-clazz-detail/clazz?plateType=' + plateType + '&evaType=' + evaType + '&weekNo=' + weekNo +
        '&tabType=' + this.data.ApprovalTab +
        '&dutyType=' + this.data.dutyTeacherType,
      })
    } else if (evaType == 1) {
      wx.navigateTo({
        url: '../appraise-clazz-detail/clazz?evaType=' + evaType + '&weekNo=' + weekNo +
        '&tabType=' + this.data.ApprovalTab +
        '&dutyType=' + this.data.dutyTeacherType,
      })
    } else {
      wx.navigateTo({
        url: '../appraise-clazz-detail/clazz?evaType=' + evaType + '&weekNo=' + weekNo + '&isLeader=' + this.data.isLeader + 
        '&gradeName2=' + this.data.teacherGradeName +
        '&clazz2=' + this.data.banZhuRenClass +
        '&tabType=' + this.data.ApprovalTab +
        '&dutyType=' + this.data.dutyTeacherType,
      })
    }
  },

  /**
   * 点击行
   */
  onRowClick(e) {
    let rowData = e.detail.currentTarget.dataset.it;
    let clazz = Number(rowData.clazz.substr(0, rowData.clazz.length - 1));
    let gradeName = rowData.grade;
    let evaType = this.data.evaLeaderType;
    let weekNo = this.data.weekList[this.data.weekListIndex].weekNo;
    if (evaType == 2) {
      let plateType = this.data.plateType;
      wx.navigateTo({
        url: '../appraise-clazz-detail/clazz?clazz=' + clazz +
          '&gradeName=' + gradeName +
          '&plateType=' + plateType +
          '&evaType=' + evaType + '&weekNo=' + weekNo +
          '&tabType=' + this.data.ApprovalTab +
          '&dutyType=' + this.data.dutyTeacherType,
      })
    } else if (evaType == 1) {
      wx.navigateTo({
        url: '../appraise-clazz-detail/clazz?clazz=' + clazz +
          '&gradeName=' + gradeName + '&evaType=' + evaType + '&weekNo=' + weekNo +
          '&tabType=' + this.data.ApprovalTab +
          '&dutyType=' + this.data.dutyTeacherType,
      })
    } else if (this.data.isLeader) {
      wx.navigateTo({
        url: '../appraise-clazz-detail/clazz?clazz=' + clazz +
          '&gradeName=' + gradeName + '&evaType=' + evaType + '&weekNo=' + weekNo + '&isLeader=' + this.data.isLeader +
          '&tabType=' + this.data.ApprovalTab +
          '&dutyType=' + this.data.dutyTeacherType,
      })
    } else {
      wx.navigateTo({
        url: '../appraise-clazz-detail/clazz?clazz2=' + clazz +
          '&gradeName2=' + gradeName +
          '&tabType=' + this.data.ApprovalTab +
          '&dutyType=' + this.data.dutyTeacherType
      })
    }
  },

  /**
   * 设置tabArray头部选择栏
   */
  setTabArray() {
    if (this.data.userType == 2) {
      return;
    }
    let dutyTeacherType = this.data.dutyTeacherType;
    let evaType = this.data.evaLeaderType;
    let tabArr = this.data.tabArray;
    if (dutyTeacherType != 0 || evaType != 0) {
      // 组长或者组员
      tabArr.push("文明班级评比");
    }
    if (evaType != 0 || this.data.isLeader || app.globalData.appUser.banZhuRen || app.globalData.appUser.jiZhang) {
      tabArr.push("班级评比统计");
    }
    this.setData({
      tabArray: tabArr
    });
    // 文明班级评比，用于下拉刷新页面
    if (this.data.tabArray[this.data.TabCur] == '文明班级评比') {
      this.setData({
        noMoreAppraisal: false,
        pageNum: 1,
        appraisalList: [],
      });
      this.onPullDownRefresh();
    }
  },

  /**
   * 加扣分单选框变更
   */
  ChangeScoreRadio(e) {
    this.setData({
      scoreType: e.detail.value
    })
  },

  /**
   * 隐藏确认审批的modal
   */
  hideAgreeModal(e) {
    this.setData({
      modalName: null,
      scoreType: 'add'
    })
  },


  /**
   * 同意评比
   */
  agreeAppraisal: function (e) {
    let score = e.detail.value.score;
    if(!score) {
      wx.showToast({title: '请打分',icon: 'none'});
      return;
    }
    if (this.data.scoreType == 'add') {
      score = Number(score);
    } else {
      score = Number('-' + score);
    }
    this.submitAgree(score);
  },
})